package shopping.front.onthefly;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import shopping.commons.BaseOnTheFlyAction;
import shopping.management.ProductAction;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 */
@org.apache.struts2.convention.annotation.Namespace("/front/onthefly")
@org.apache.struts2.convention.annotation.ParentPackage(value = "shopping-json-default")
@org.apache.struts2.convention.annotation.InterceptorRefs({
        @org.apache.struts2.convention.annotation.InterceptorRef("jsonValidationWorkflowStack"),
        @org.apache.struts2.convention.annotation.InterceptorRef("defaultStack")
})
public class ProductImageListAction extends BaseOnTheFlyAction {

    private int productId;

    private List<String> images = new ArrayList<String>();

    public List<String> getImages() {
        return images;
    }

    public void setImages(List<String> images) {
        this.images = images;
    }

    public int getProductId() {
        return productId;
    }

    public void setProductId(int productId) {
        this.productId = productId;
    }

    @Action(value = "/front/onthefly/listimages",
            results = {
                    @Result(name = "success", type = "json")
            }
    )
    public String listImages() {
        if (log.isDebugEnabled()) {
            log.debug("enter front onthe fly listimages action");
            log.debug("productId:" + productId);
        }
        String uploadDir = getText(ProductAction.KEY_PRODUCT_IMAGE_DIR);
        File baseDir = new File(uploadDir + "/" + productId);

        log.debug("base dir:" + baseDir.getAbsolutePath());

        String[] files = baseDir.list(new FilenameFilter() {

            public boolean accept(File dir, String name) {
                //@todo: add all supported image types
                return true;
            }
        });

        if (images == null) {
            images = new ArrayList<String>();
        }
        images.clear();
        log.debug("after initialization of list");

        for (String file : files) {
            images.add("/" + productId + "/" + file);
        }

        log.debug("image list:" + images.size());

        return SUCCESS;
    }
}
